package com.qian.ddj.web.controller;

import com.qian.api.ddj.model.BusinessCard;
import com.qian.api.ddj.model.Cash;
import com.qian.api.ddj.model.CashQueryModel;
import com.qian.api.ddj.model.StatusDict;
import com.qian.api.ddj.service.IBusinessCardService;
import com.qian.api.ddj.service.ICashService;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.web.system.security.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ddj/cash")
@Api(tags = "提现管理")
public class CashController {

    @Autowired
    private ICashService cashService;
    @Autowired
    private IBusinessCardService businessCardService;

    @GetMapping
    @ApiOperation("用户提现列表")
    public PageResp<Cash> list(CashQueryModel cash, PageReq pageReq) {
        cash.setUserId(SecurityUtils.getUserId());
        PageResp<Cash> page = cashService.findAll(cash, pageReq);
        return page;
    }

    @GetMapping("/all")
    @ApiOperation("所有提现列表")
    public PageResp<Cash> listAll(CashQueryModel cash, PageReq pageReq) {
        PageResp<Cash> page = cashService.findAll(cash, pageReq);
        return page;
    }

    @GetMapping("/export")
    @ApiOperation("用户提现导出")
    public void list(CashQueryModel cash, HttpServletResponse response) {
        if (cash.getBeginTime() == null) {
            throw new BaseException("开始时间不能为空");
        }
        long time = 7 * 24 * 60 * 60 * 1000;
        if (new Date().getTime() - cash.getBeginTime().getTime() > time && cash.getEndTime().getTime() - cash.getBeginTime().getTime() > time) {
            throw new BaseException("时间不能超过一个星期");
        }

        cash.setUserId(SecurityUtils.getUserId());
        PageReq pageReq = new PageReq();
        pageReq.setPageSize(Integer.MAX_VALUE);
        PageResp<Cash> pageResp = cashService.findAll(cash, pageReq);

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell0 = row.createCell(0);
        XSSFCell cell1 = row.createCell(1);
        XSSFCell cell2 = row.createCell(2);
        XSSFCell cell3 = row.createCell(3);
        XSSFCell cell4 = row.createCell(4);
        XSSFCell cell5 = row.createCell(5);
        XSSFCell cell6 = row.createCell(6);
        XSSFCell cell7 = row.createCell(7);
        XSSFCell cell8 = row.createCell(8);
        XSSFCell cell9 = row.createCell(9);
        cell0.setCellValue("提现金额");
        cell1.setCellValue("手续费");
        cell2.setCellValue("手机号");
        cell3.setCellValue("银行名称");
        cell4.setCellValue("卡号");
        cell5.setCellValue("持卡人");
        cell6.setCellValue("备注");
        cell7.setCellValue("处理结果");
        cell8.setCellValue("申请时间");
        cell9.setCellValue("处理时间");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Cash> cashList = pageResp.getList();
        int i = 1;
        for (Cash o : cashList) {
            row = sheet.createRow(i);
            cell0 = row.createCell(0);
            cell1 = row.createCell(1);
            cell2 = row.createCell(2);
            cell3 = row.createCell(3);
            cell4 = row.createCell(4);
            cell5 = row.createCell(5);
            cell6 = row.createCell(6);
            cell7 = row.createCell(7);
            cell8 = row.createCell(8);
            cell9 = row.createCell(9);
            cell0.setCellValue(o.getMoney().toString());
            cell1.setCellValue(o.getFee().toString());
            cell2.setCellValue(o.getCardPhone());
            cell3.setCellValue(o.getCardBank());
            cell4.setCellValue(o.getCardNo());
            cell5.setCellValue(o.getCardPerson());
            cell6.setCellValue(o.getRemark());
            if (StatusDict.CASH_SUCCESS.equals(o.getStatus())) {
                cell7.setCellValue("成功");
            } else if (StatusDict.CASH_FAIL.equals(o.getStatus())) {
                cell7.setCellValue("失败");
            } else {
                cell7.setCellValue("待处理");
            }

            if (ObjectUtils.allNotNull(o.getCreateTime())) {
                cell8.setCellValue(dateFormat.format(o.getCreateTime()));
            }
            if (ObjectUtils.allNotNull(o.getFinishTime())) {
                cell9.setCellValue(dateFormat.format(o.getFinishTime()));
            }

            i++;
        }

        row = sheet.createRow(i);
        cell0 = row.createCell(0);
        cell1 = row.createCell(1);
        cell2 = row.createCell(2);
        cell3 = row.createCell(3);
        cell4 = row.createCell(4);
        cell5 = row.createCell(5);
        cell6 = row.createCell(6);
        cell7 = row.createCell(7);
        cell0.setCellValue("总金额");
        cell1.setCellValue("成功金额");
        cell2.setCellValue("失败金额");
        cell3.setCellValue("待处理金额");
        cell4.setCellValue("总数");
        cell5.setCellValue("成功数");
        cell6.setCellValue("失败数");
        cell7.setCellValue("待处理数");
        Map map = count(cashList);
        i++;
        row = sheet.createRow(i);
        cell0 = row.createCell(0);
        cell1 = row.createCell(1);
        cell2 = row.createCell(2);
        cell3 = row.createCell(3);
        cell4 = row.createCell(4);
        cell5 = row.createCell(5);
        cell6 = row.createCell(6);
        cell7 = row.createCell(7);
        cell0.setCellValue(String.valueOf(map.get("totalMoney")));
        cell1.setCellValue(String.valueOf(map.get("successMoney")));
        cell2.setCellValue(String.valueOf(map.get("failMoney")));
        cell3.setCellValue(String.valueOf(map.get("waitMoney")));
        cell4.setCellValue(String.valueOf(map.get("totalNumber")));
        cell5.setCellValue(String.valueOf(map.get("successNumber")));
        cell6.setCellValue(String.valueOf(map.get("failNumber")));
        cell7.setCellValue(String.valueOf(map.get("waitNumber")));


        String fileName = SecurityUtils.getUserInfo().getUsername() + "cash.xls";
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/count")
    @ApiOperation("用户提现统计")
    public Map count(CashQueryModel cashQueryModel) {
        cashQueryModel.setUserId(SecurityUtils.getUserId());
        PageReq req = new PageReq();
        req.setPageSize(Integer.MAX_VALUE);
        PageResp<Cash> all = cashService.findAll(cashQueryModel, req);
        return count(all.getList());
    }

    @GetMapping("/count/all")
    @ApiOperation("后台提现统计")
    public Map countAll(CashQueryModel cashQueryModel) {
        PageReq req = new PageReq();
        req.setPageSize(Integer.MAX_VALUE);
        PageResp<Cash> all = cashService.findAll(cashQueryModel, req);
        return count(all.getList());
    }

    @GetMapping("/businessCard")
    @ApiOperation("用户提现银行卡列表")
    public List<BusinessCard> businessCardList() {
        List<BusinessCard> list = businessCardService.findByUserId(SecurityUtils.getUserId());
        return list;
    }

    @PostMapping()
    @ApiOperation("提现申请")
    public void cash(Cash cash) {
        cash.setUserId(SecurityUtils.getUserId());
        cashService.cash(cash);
    }

    @GetMapping("/success/{id}")
    @ApiOperation("提现成功")
    public void success(@PathVariable Integer id, String remark) {
        Cash cash = new Cash();
        cash.setId(id);
        cash.setRemark(remark);
        cash.setStatus(StatusDict.CASH_SUCCESS);
        cashService.save(cash);
    }

    @GetMapping("/fail/{id}")
    @ApiOperation("提现失败")
    public void fail(@PathVariable Integer id, String remark) {
        Cash cash = new Cash();
        cash.setId(id);
        cash.setRemark(remark);
        cash.setStatus(StatusDict.CASH_FAIL);
        cashService.save(cash);
    }

    private Map count(List<Cash> cashs) {
        Integer successNumber = 0;
        Integer failNumber = 0;
        Integer waitNumber = 0;
        Integer totalNumber = 0;
        BigDecimal totalMoney = BigDecimal.ZERO;
        BigDecimal successMoney = BigDecimal.ZERO;
        BigDecimal failMoney = BigDecimal.ZERO;
        BigDecimal waitMoney = BigDecimal.ZERO;
        for (Cash order : cashs) {
            totalNumber++;
            totalMoney = totalMoney.add(order.getTotal());
            if (order.getStatus().equals(StatusDict.CASH_SUCCESS)) {
                successNumber++;
                successMoney = successMoney.add(order.getTotal());
            } else if (order.getStatus().equals(StatusDict.CASH_FAIL)) {
                failNumber++;
                failMoney = failMoney.add(order.getTotal());
            } else if (order.getStatus().equals(StatusDict.NORMAL)) {
                waitNumber++;
                waitMoney = waitMoney.add(order.getTotal());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("totalNumber", totalNumber);
        map.put("successNumber", successNumber);
        map.put("failNumber", failNumber);
        map.put("waitNumber", waitNumber);
        map.put("totalMoney", totalMoney);
        map.put("successMoney", successMoney);
        map.put("failMoney", failMoney);
        map.put("waitMoney", waitMoney);
        return map;
    }

}